package com.czy.owner.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.owner.R;
import com.czy.owner.api.DeleteManintenanceApi;
import com.czy.owner.api.OwnerCarApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.MaintenanceRecord;
import com.czy.owner.entity.TextingListModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.archive.ArchiveAddActivity;
import com.czy.owner.ui.archive.ArchiveEditActivity;
import com.czy.owner.ui.archive.MaintenanceRecordActivity;
import com.czy.owner.ui.archive.TestingDetailsActivity;
import com.czy.owner.ui.archive.TestingListActivity;
import com.czy.owner.ui.store.OnLineOrderActivity2;
import com.czy.owner.ui.workorder.OrderDetailsActivity3;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easyrecycleview.adapter.BaseViewHolder;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import butterknife.ButterKnife;

/**
 * Created by hedepu on 2017/12/21 0001.
 */
public class MaintenanceRecordAdapter extends RecyclerArrayAdapter<MaintenanceRecord> {
    private onCustomClickListener customListener = null;
    private OnEditClickListener onEditClickListener;

    public OnEditClickListener getOnEditClickListener() {
        return onEditClickListener;
    }

    public void setOnEditClickListener(OnEditClickListener onEditClickListener) {
        this.onEditClickListener = onEditClickListener;
    }


    private Context context;

    public MaintenanceRecordAdapter(Context context) {
        super(context);
        this.context = context;
    }


    @Override
    public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
        return new MaintenanceRecordViewHolder(parent);
    }
//        return new MaintenanceRecordViewHolder(layoutInflater.inflate(R.layout.item_maintenance_record_recycler_2, parent, false));


    public class MaintenanceRecordViewHolder extends BaseViewHolder<MaintenanceRecord> {
        //        private TextView tvDateMonth, tvDateDay, tvType, tvDate, tvAmount, tvMileage, tvRemark, tvMaintenanceSystem;
//        private LinearLayout linearEdit, linearDelete;
        private TextView tvMaintainType, tvMaintainTime, tvMaintainKilometre, tvMaintainMoney, tvNextTimeTime, tvNextTimeKill, tvMaintainNoto, tvNotoTitle, btEdit, btDelete;
        private RecyclerView recylerViewServiceItems;
        private LinearLayout linearNextTimeTime, linearNextTimeLill;
        private RelativeLayout relatMaintainNoto, relatMaintainMoney, relatMaintainKilometre;

        public MaintenanceRecordViewHolder(ViewGroup parent) {
            super(parent, R.layout.item_maintenance_record_recycler_2);

            tvMaintainType = (TextView) itemView.findViewById(R.id.tv_maintain_type);
            tvMaintainTime = (TextView) itemView.findViewById(R.id.tv_maintain_time);
            tvMaintainKilometre = (TextView) itemView.findViewById(R.id.tv_maintain_kilometre);
            tvMaintainMoney = (TextView) itemView.findViewById(R.id.tv_maintain_money);
            tvMaintainNoto = (TextView) itemView.findViewById(R.id.tv_maintain_noto);
            tvNextTimeTime = (TextView) itemView.findViewById(R.id.tv_next_time_time);
            tvNextTimeKill = (TextView) itemView.findViewById(R.id.tv_next_time_kill);
            btEdit = (TextView) itemView.findViewById(R.id.bt_edit);
            btDelete = (TextView) itemView.findViewById(R.id.bt_delete);
            tvNotoTitle = (TextView) itemView.findViewById(R.id.tv_noto_title);

            recylerViewServiceItems = (RecyclerView) itemView.findViewById(R.id.recyler_view_service_items);
            linearNextTimeTime = (LinearLayout) itemView.findViewById(R.id.linear_next_time_time);
            linearNextTimeLill = (LinearLayout) itemView.findViewById(R.id.linear_next_time_kill);
            relatMaintainNoto = (RelativeLayout) itemView.findViewById(R.id.relat_maintain_noto);
            relatMaintainMoney = (RelativeLayout) itemView.findViewById(R.id.relat_maintain_money);
            relatMaintainKilometre = (RelativeLayout) itemView.findViewById(R.id.relat_maintain_kilometre);
        }

        @Override
        public void setData(final MaintenanceRecord mRecord) {
            super.setData(mRecord);
            Date date = new Date(mRecord.getServiceTime());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            tvMaintainTime.setText(format.format(date));
//            String[] dateArray = format.format(date).split("-");
//            tvDateMonth.setText(dateArray[1] + "月");
//            tvDateDay.setText(dateArray[2]);
            if ("owner".equals(mRecord.getCreateType())) {
                tvMaintainType.setText("自助保养");
                btEdit.setVisibility(View.VISIBLE);
            } else {
                btEdit.setVisibility(View.GONE);
                tvMaintainType.setText("门店保养");
            }
            if ("inspectionOrder".equals(StringUtils.getString(mRecord.getOrderType(), ""))) {
                relatMaintainMoney.setVisibility(View.GONE);
            } else {
                relatMaintainMoney.setVisibility(View.VISIBLE);
            }
//            tvType.setText("消费类型：" + (TextUtils.isEmpty(mRecord.getTypeName()) ? mRecord.getServiceName() : mRecord.getTypeName()));
            if (mRecord.getPrice() == 0) {
                relatMaintainMoney.setVisibility(View.GONE);
            } else {
                relatMaintainMoney.setVisibility(View.VISIBLE);
                tvMaintainMoney.setText("¥" + DecimalUtil.formatNum(mRecord.getPrice() + ""));
            }


            if (mRecord.getCurrentMileage() == 0) {
                relatMaintainKilometre.setVisibility(View.GONE);
            } else {
                relatMaintainKilometre.setVisibility(View.VISIBLE);
                tvMaintainKilometre.setText(mRecord.getCurrentMileage() + "km");
            }

            if (("未设置".equals(mRecord.getNote()) || StringUtils.isEmpty(mRecord.getNote())) && StringUtils.isEmpty(mRecord.getOrderNote())) {
                tvMaintainNoto.setVisibility(View.GONE);
                tvNotoTitle.setVisibility(View.GONE);
            } else if (!StringUtils.isEmpty(mRecord.getOrderNote())) {
                tvMaintainNoto.setVisibility(View.VISIBLE);
                tvNotoTitle.setVisibility(View.VISIBLE);
                tvMaintainNoto.setText(mRecord.getOrderNote());
            } else {
                tvMaintainNoto.setVisibility(View.VISIBLE);
                tvNotoTitle.setVisibility(View.VISIBLE);
                tvMaintainNoto.setText(mRecord.getNote());
            }
            recylerViewServiceItems.setLayoutManager(new LinearLayoutManager(context));
            MaintenanceRecordChildAdapter maintenanceRecordChildAdapter = new MaintenanceRecordChildAdapter(context, mRecord.getItemList());
            maintenanceRecordChildAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<MaintenanceRecord.DataBeanModel>() {
                @Override
                public void onItemClick(int position, MaintenanceRecord.DataBeanModel dataBeanModel, View view) {
                    if ("inspectionOrder".equals(StringUtils.getString(dataBeanModel.getType(), ""))) {
                        context.startActivity(new Intent(context, TestingDetailsActivity.class)
                                .putExtra("userOrderId", mRecord.getUserOrderId())
                                .putExtra("storeId", mRecord.getStoreId()));
                    } else if ("serviceOrder".equals(StringUtils.getString(mRecord.getOrderType(), ""))) {
                        context.startActivity(new Intent(context, OrderDetailsActivity3.class)
                                .putExtra("userOrderId", mRecord.getUserOrderId())
                                .putExtra("orderNumber", mRecord.getOrderNumber())
                                .putExtra("storeId", mRecord.getStoreId()));
                    }
                }
            });
//            recylerViewServiceItems.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL, R.drawable.shape_shopping_white_divider_decoration));
            if (mRecord.getNextTime() == 0) {

                linearNextTimeTime.setVisibility(View.GONE);
            } else {
                Date nextDate = new Date(mRecord.getNextTime());
                SimpleDateFormat nextFormat = new SimpleDateFormat("yyyy-MM-dd");
                nextFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                linearNextTimeTime.setVisibility(View.VISIBLE);
                tvNextTimeTime.setText(nextFormat.format(nextDate));
            }
            if (mRecord.getNextMileage() == 0) {
                linearNextTimeLill.setVisibility(View.GONE);

            } else {
                linearNextTimeLill.setVisibility(View.VISIBLE);
                tvNextTimeKill.setText(+mRecord.getNextMileage() + "km");
            }
            recylerViewServiceItems.setAdapter(maintenanceRecordChildAdapter);
//
            btDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new UniversalDialog(context).builder()
                            .setCancelable(false)
                            .setTitle("确定删除记录")
                            .setMsg("确定删除该记录，删除后不可恢复")
                            .setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                }
                            }).setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            deletaData(mRecord.getCarFilesRecordId() + "", mRecord);
//
                        }
                    }).show();
//
//
                }
            });
            btEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onEditClickListener != null)
                        onEditClickListener.onEdit(mRecord);

                }
            });
        }
    }

    //删除养车记录final int position
    private void deletaData(String carFilesRecordId, final MaintenanceRecord maintenanceRecord) {
        DeleteManintenanceApi deleteManintenanceApi = new DeleteManintenanceApi(new HttpOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                if (onEditClickListener != null)
                    onEditClickListener.onDelete();
//                mObjects.remove(maintenanceRecord);
//                notifyDataSetChanged();
//                notifyItemRemoved(position);
//                if (position != mObjects.size())
//                    notifyItemRangeChanged(position, mObjects.size() - position);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
//                Toast.makeText(mContext, "", Toast.LENGTH_SHORT).show();
            }
        }, (RxAppCompatActivity) context);
        deleteManintenanceApi.setSession(UserHelper.getInstance().

                getSession(context));
        deleteManintenanceApi.setCarFilesRecordId(carFilesRecordId);
        HttpManager.getInstance().

                doHttpDeal(deleteManintenanceApi);
    }

    public interface OnEditClickListener {
        void onEdit(MaintenanceRecord m);

        void onDelete();
    }

    public interface onCustomClickListener<T> {
        public boolean onClick(T t);
    }
}
